<template>
	<view>
		<view>
			<view v-if="showTitle" class="orderDetailTitle">{{title}}</view>

			<view class="bgfff" :style="{'padding':padding}">
				<template v-if="mode == 'upload'">
					<view class="display_flex">
						<view v-if="thisImage && thisImage.length > 0"
							style="position: relative;width: 160rpx;height: 160rpx;" v-for="(url,index) in thisImage"
							:key="index" class="primaryBor">
							<el-image :src="url" style="width: 100%;height: 100%;" :preview-src-list="[url]"
								fit="contain" />
							<view style="position: absolute;top: -15rpx;right: -8rpx;" @click="removeImg(index)">
								<i class="el-icon-circle-close u-type-error" style="font-size: 30px;" />
							</view>
						</view>
						<view style="width: 170rpx;line-height: 160rpx;text-align:center;border-radius:16rpx"
							@click="upload_image" v-if="thisImage.length < imageNum" class="primaryBor">
							<i class="el-icon-upload2" style="font-size: 30px;" />
						</view>
					</view>
				</template>

				<template v-if="mode == 'preview'">
					<view class="display_flex">
						<view v-if="thisImage && thisImage.length > 0" style="position: relative;"
							v-for="(url,index) in thisImage" :key="index">
							<image :src="url" style="width: 170rpx;height: 170rpx;margin-right: 10rpx;" mode="aspectFit"
								@click="priviewImg(url)"></image>
						</view>
					</view>
				</template>

			</view>

		</view>
	</view>
</template>

<script>
	import UUID from 'uuid';
	// import COS from 'cos-js-sdk-v5'; // 改用后端上传，不再需要前端SDK
	// import chooseAndUploadImage from '@/js_sdk/tencentcloud/uploadImage'; // 暂时不使用

	export default {
		props: {
			padding: {
				type: String,
				default: "20rpx"
			},
			imageNum: {
				type: Number,
				default: 100
			}, // 标题
			canSetHeader: {
				type: Boolean,
				default: false,
			}, //是否可以设置主图
			Images: {
				type: [Array, Object],
				default: []
			},
			mode: {
				type: "",
				default: "upload"
			},
			title: {
				type: String,
				default: "上传凭证图"
			},
			showTitle: {
				type: Boolean,
				default: true,
			},
			artPptNum: {
				type: String,
				default: "课件编号"
			},
		},

		watch: {
			Images: function(n, o) {
				if (n && n.length > 0) {
					this.thisImage = []
					for (let item of n) {
						if (item) {
							this.thisImage.push(item)
						}
					}
				} else {
					this.thisImage = []
				}
			}
		},

		data() {
			return {
				thisImage: []
			};
		},

		mounted() {

			this.thisImage = []
			if (this.Images.length > 0) {
				for (let image of this.Images) {
					if (image) {
						this.thisImage.push(image)
					}
				}
			}
		},

		methods: {
			//设置此图片为主图
			setHeader(index) {
				let that = this
				if (this.canSetHeader == false) return;
				uni.showModal({
					content: "是否将此图片设置为主图",
					success(res) {
						if (res.confirm) {
							let str = that.thisImage.splice(index, 1);
							that.thisImage.unshift(str[0]);
							that.$emit("setHeader", that.thisImage)
						}
					}
				})
			},

			async upload_image() {
				// 使用腾讯云COS上传（上海存储桶）
				uni.chooseImage({
					count: this.imageNum, //最多可以选择的图片张数，默认9
					sizeType: ['compressed'], //强制使用压缩图
					sourceType: ['album', 'camera'], //album 从相册选图，camera 使用相机，默认二者都有
					success: res => {
						this.useTencentCOS_upload(res.tempFiles); // 调用腾讯云上传
					}
				});
			},

			// 腾讯云COS上传方法（通过后端接口上传，避免CORS问题）
			async useTencentCOS_upload(files) {
				let that = this;

				// 显示加载提示
				uni.showLoading({
					title: '上传中...',
					mask: true
				});

				let promises = [];

				for (let file of files) {
					let promise = new Promise(function(resolve, reject) {
						// 使用 uni.uploadFile 上传到后端接口
						uni.uploadFile({
							url: that.$http.baseUrl + 'txMac/uploadCosImage', // 后端上传接口
							filePath: file.path,
							name: 'file',
							formData: {
								'artPptNum': that.artPptNum // 传递课件编号
							},
							success: (uploadFileRes) => {
								try {
									const result = JSON.parse(uploadFileRes.data);
									if (result.code === 200) {
										console.log('上传成功:', result.data.url);
										resolve(result.data.url);
									} else {
										console.error('上传失败:', result.msg);
										reject(new Error(result.msg));
									}
								} catch (err) {
									console.error('解析响应失败:', err);
									reject(err);
								}
							},
							fail: (err) => {
								console.error('上传失败:', err);
								reject(err);
							}
						});
					});
					promises.push(promise);
				}

				// 等待所有文件上传完成
				Promise.all(promises).then(function(res) {
					console.log('上传成功:', res);
					uni.hideLoading();
					uni.showToast({
						title: '上传成功',
						icon: 'success'
					});
					that.thisImage = that.thisImage.concat(res);
					that.$emit("upload", that.thisImage);
				}).catch(function(err) {
					console.error('上传失败:', err);
					uni.hideLoading();
					uni.showToast({
						title: '上传失败: ' + err.message,
						icon: 'none'
					});
				});
			},


			// 【已废弃 - 七牛云上传方法，保留用于回滚】
			async useQiniiyun_upload(files) {
				let that = this

				let promises = []
				for (let file of files) {
					let promise = new Promise(function(resolve, reject) {

						let filePath = undefined;
						let fileExt;
						if (typeof file === 'string') {
							filePath = file;
							file = undefined;
							fileExt = filePath.split('?')[0].split('.').pop();
						} else {
							fileExt = file.name.split('.').pop();
						}
						// 支付宝小程序上传文件API必传fileType
						// 通过支付宝小程序环境下选择文件的时候，通过返回的filePath取得的扩展名可能是image/video/audio
						let fileType = undefined;
						// ifdef MP-ALIPAY
						if (fileExt === 'image') {
							fileExt = 'jpg';
						} else if (fileExt === 'video') {
							fileExt = 'mp4';
						} else if (fileExt === 'audio') {
							fileExt = 'mp3';
						} else if (fileExt === 'zip') {
							fileExt = 'zip';
						}
						fileType = that.getMediaType(fileExt);
						let fileName = `${UUID.v1()}.${fileExt}`;
						/**
						 * 参数：
						 * 1.file：要上传的文件选择器或者文件对象
						 *2. filename_qn：上传到七牛后保存的文件名。如果不指定，则由七牛服务器自动生成。
						 *3. token：上传凭证，详见 上传策略
						 */
						// 上传以后的文件名-存在七牛云的文件名字-空间的域名+文件名就可以访问文件了！最好做时间戳+随机数这样做一个唯一的文件名字
						const filename_qn = that.common.getDay(0) + "/" + that.artPptNum + "/" + fileName;
						// console.log('上传前生成的文件名字：', filename_qn)
						// 发起请求,获取上传文件需要的uploadToken
						that.$http.Post("user/getToken", {
							fileName: fileName
						}).then(res => {
							const token = res.data;
							// 获取成功后发起文件上传
							/**
							 * url:我这里是（https://upload-z2.qiniup.com）：华南-广东 对应的七牛云的地址-其他的可以自行百度
							 * filePath：文件本地临时地址，一次只能一个，字符串类型
							 */
							uni.uploadFile({
								url: 'https://upload-cn-east-2.qiniup.com',
								filePath: file.path,
								name: 'file',
								formData: {
									'key': filename_qn, // 存到七牛云后的文件名字，访问图片会用到
									'token': token, // uploadToken，需要动态获取，调用云函数接口获取
								},
								// 存成功后的回调
								success: (uploadFileRes) => {
									let key = JSON.parse(uploadFileRes.data).key;
									// 空间绑定的域名（在七牛云配置）+key就是文件的访问地址
									const img_url = 'https://qiniu.jimuzhou.cloud/' + key
									resolve(img_url)
								},
								fail: (err) => {
									console.log('上传失败了', err);
									uni.hideLoading();
								}
							});

						})
					})
					promises.push(promise)
				}
				Promise.all(promises).then(function(res) {
					console.log(res)
					that.thisImage = that.thisImage.concat(res)
					that.$emit("upload", that.thisImage)
				});
			},

			getMediaType(ext) {
				if (/^(jpg|jpeg|png|gif|bmp|webp)$/.test(ext.toLowerCase())) {
					return 'image';
				}
				if (/^(mp4|mpeg|qsv|mov|avi|3gp)$/.test(ext.toLowerCase())) {
					return 'video';
				}
				if (/^(mp3|wma|wav|m4a)$/.test(ext.toLowerCase())) {
					return 'audio';
				}
				return 'other';
			},

			//移除此张照片
			removeImg(index) {
				let that = this;

				// TODO: 当前使用上海存储桶，后端deleteCosFile接口配置的是南京存储桶，暂时无法删除
				// 仅前端删除显示，实际文件仍保留在COS中
				// 后续需要后端接口支持上海存储桶或传递存储桶参数

				// 使用 $confirm 替代 uni.showModal 避免被 el-dialog 遮挡
				this.$confirm('确定删除这张图片吗？（注意：当前仅删除显示，实际文件仍保留在云端）', '提示', {
					confirmButtonText: '确定',
					cancelButtonText: '取消',
					type: 'warning'
				}).then(() => {
					that.thisImage.splice(index, 1);
					that.$emit("remove", that.thisImage);
					this.$message({
						type: 'success',
						message: '已移除'
					});
				}).catch(() => {
					// 取消删除
				});

				// 原七牛云/南京存储桶删除接口（已注释）
				// that.$http.Post("txMac/deleteCosFile", {
				// 	imageUrl: that.thisImage[index]
				// }, "删除中").then(res => {
				// 	console.log(res)
				// 	that.thisImage.splice(index, 1)
				// 	that.$emit("remove", this.thisImage)
				// })
			},

			priviewImg(url) {
				uni.previewImage({
					urls: [url],
				})
			},
		}

	}
</script>

<style scoped>
/* ==================== 容器样式 ==================== */
.bgfff {
	background: transparent;
}

/* ==================== 标题样式 ==================== */
.orderDetailTitle {
	color: #00d4ff;
	font-size: 14px;
	font-weight: 600;
	margin-bottom: 15px;
	padding-left: 12px;
	border-left: 3px solid #00d4ff;
	text-shadow: 0 0 10px rgba(0, 212, 255, 0.3);
	letter-spacing: 0.5px;
}

/* ==================== Flex 布局 ==================== */
.display_flex {
	display: flex;
	flex-wrap: wrap;
	gap: 15px;
}

/* ==================== 图片容器样式 ==================== */
.primaryBor {
	position: relative;
	border: 2px solid rgba(0, 212, 255, 0.3) !important;
	border-radius: 12px;
	background: rgba(15, 20, 40, 0.4);
	margin-right: 0 !important;
	transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
	overflow: hidden;
	box-shadow:
		0 4px 12px rgba(0, 0, 0, 0.2),
		inset 0 1px 0 rgba(255, 255, 255, 0.05);
}

.primaryBor:hover {
	border-color: #00d4ff !important;
}

/* 图片预览样式增强 */
.primaryBor::before {
	content: '';
	position: absolute;
	top: 0;
	left: 0;
	right: 0;
	bottom: 0;
	background: linear-gradient(135deg, rgba(0, 212, 255, 0.1) 0%, transparent 100%);
	opacity: 0;
	transition: opacity 0.3s ease;
	pointer-events: none;
	z-index: 1;
}

/* ==================== 上传按钮样式 ==================== */
view[class*="primaryBor"][style*="line-height"] {
	background: linear-gradient(135deg, rgba(0, 212, 255, 0.1) 0%, rgba(0, 132, 255, 0.1) 100%);
	border: 2px dashed rgba(0, 212, 255, 0.4) !important;
	cursor: pointer;
	position: relative;
	overflow: hidden;
}

view[class*="primaryBor"][style*="line-height"]:hover {
	background: linear-gradient(135deg, rgba(0, 212, 255, 0.2) 0%, rgba(0, 132, 255, 0.2) 100%);
	border-color: #00d4ff !important;
}

/* ==================== 上传图标样式 ==================== */
.el-icon-upload2 {
	color: #00d4ff !important;
	font-size: 30px !important;
	transition: all 0.3s ease;
	position: relative;
	z-index: 2;
	filter: drop-shadow(0 0 8px rgba(0, 212, 255, 0.4));
}

view[class*="primaryBor"][style*="line-height"]:hover .el-icon-upload2 {
	color: #00e4ff !important;
}

/* ==================== 删除按钮样式 ==================== */
.el-icon-circle-close {
	color: rgba(255, 107, 157, 0.8) !important;
	font-size: 28px !important;
	cursor: pointer;
	transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
	filter: drop-shadow(0 2px 4px rgba(0, 0, 0, 0.3));
	background: rgba(15, 20, 40, 0.9);
	border-radius: 50%;
	position: relative;
	z-index: 10;
}

.el-icon-circle-close:hover {
	color: #ff6b9d !important;
}

/* ==================== 图片样式优化 ==================== */
.primaryBor .el-image {
	border-radius: 10px;
	overflow: hidden;
}

/* 图片加载动画 */
@keyframes imageLoading {
	0%, 100% {
		opacity: 0.6;
	}
	50% {
		opacity: 1;
	}
}

/* ==================== 预览模式图片样式 ==================== */
image {
	border: 2px solid rgba(0, 212, 255, 0.3);
	border-radius: 12px;
	transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
	cursor: pointer;
	background: rgba(15, 20, 40, 0.4);
	box-shadow:
		0 4px 12px rgba(0, 0, 0, 0.2),
		inset 0 1px 0 rgba(255, 255, 255, 0.05);
}

image:hover {
	border-color: #00d4ff;
}

/* ==================== 响应式优化 ==================== */
@media (max-width: 768px) {
	.display_flex {
		gap: 10px;
	}

	.orderDetailTitle {
		font-size: 13px;
		margin-bottom: 12px;
	}
}

/* ==================== 全局文字颜色 ==================== */
view {
	color: rgba(255, 255, 255, 0.9);
}

/* ==================== 错误提示颜色 ==================== */
.u-type-error {
	color: #ff6b9d !important;
}
</style>
